package com.mac.intellect_flow.framework.util;

import com.mac.intellect_flow.base.UserBaseDto;
import com.mac.intellect_flow.enums.ResultCodeEnum;
import com.mac.intellect_flow.except.ServiceException;
import com.mac.intellect_flow.framework.model.LoginUser;
import com.mac.intellect_flow.util.servlet.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;


@Slf4j
@Component
public class TokenUtil {

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 10 * 60 * 1000L;


    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {
        // 获取请求携带的令牌
        String token = JwtUtil.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            try {
                String loginRedisKey = JwtUtil.getAdminLoginRedisKey(token);
                // 解析对应的权限以及用户信息
                LoginUser user = JwtUtil.redisUtil.getCacheObject(loginRedisKey);
                return user;
            } catch (Exception e) {
                log.error("获取用户信息异常'{}'", e.getMessage());
                throw new ServiceException(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(),"非法token");
            }
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (Objects.nonNull(loginUser)) {
            JwtUtil.setRedisUserInfo(null,loginUser.getToken(),loginUser,true);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            JwtUtil.delRedisLoginUser(null,token,true);
        }
    }

    /**
     * 创建令牌
     *
     * @param loginUser 用户信息
     * @return 令牌
     */
    public String createToken(UserBaseDto loginUser) {
        return JwtUtil.createToken(loginUser.getId(), loginUser.getUsername());
    }

    /**
     * 验证令牌有效期，相差不足10分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(UserBaseDto loginUser) {
        HttpServletRequest request = ServletUtils.getRequest();
        String token = JwtUtil.getToken(request);
        JwtUtil.verifyToken(token,true,loginUser);
    }

}
